package com.xjl.handler.security;

import com.alibaba.fastjson.JSON;
import com.xjl.domain.ResponseResult;
import com.xjl.enums.AppHttpCodeEnum;
import com.xjl.utils.WebUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        e.printStackTrace();

        /**
         * InsufficientAuthenticationException 权限不足，报这个异常
         * BadCredentialsException 用户名密码错了，报这个异常
         */

        ResponseResult result = null;
        if (e instanceof BadCredentialsException) {
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), e.getMessage());
        } else if (e instanceof InsufficientAuthenticationException){
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else {
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败");
        }

            //响应给前端
            //我对WebUtils的理解，它是将原本错误的返回语句（例如403forbidden语句）全部变成200（正确返回）,将错误信息以json格式返回
            WebUtils.renderString(response, JSON.toJSONString(result));

    }
}
